﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cesave.Domain.PermisosModule.Entities;
using System.Windows.Forms;
using System.ComponentModel;
using Cesave.Application.Permisos.ServiceAgent;

namespace Cesave.Presentation.Permisos.WinForms.Client.ViewModels.Catalogs.CiclosFechas
{
	public partial class CiclosFechasViewModel
	{
		#region Private properties

		/// <summary>
		/// 
		/// </summary>
		private List<Ciclo> _ciclos;

		/// <summary>
		/// 
		/// </summary>
		private Ciclo _ciclo;

		#endregion

		#region Public properties

		/// <summary>
		/// 
		/// </summary>
		public List<Ciclo> Ciclos
		{
			get
			{
				return _ciclos;
			}
			set
			{
				_ciclos = value;
				if (_ciclos != null)
					RaisePropertyChanged("Ciclos");
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public Ciclo Ciclo
		{
			get
			{
				return _ciclo;
			}
			set
			{
				_ciclo = value;
				if (_ciclo != null)
					RaisePropertyChanged("Ciclo");
			}
		}

		#endregion

		#region Private methods

		/// <summary>
		/// 
		/// </summary>
		private void LoadCiclos()
		{
			StartWaiting();
			using (BackgroundWorker worker = new BackgroundWorker())
			{
				worker.DoWork += (sender, e) =>
				{
					using (PermisosModuleServiceWrapper service = new PermisosModuleServiceWrapper())
					{
						e.Result = service.FindAllCiclos();
					}
				};
				worker.RunWorkerCompleted += (sender, e) =>
				{
					EndWaiting();
					if (!e.Cancelled && e.Error == null)
						Ciclos = e.Result as List<Ciclo>;
					else if (e.Error != null)
						ShowMessage(e.Error.Message);
				};
				worker.WorkerSupportsCancellation = true;
				worker.RunWorkerAsync();
			}
		}

		#endregion

		#region Event methods

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void SetCurrentCiclo(object sender, EventArgs e)
		{
			BindingSource bindingSource = sender as BindingSource;
			if ((bindingSource != null) && (bindingSource.Current != null))
				Ciclo = bindingSource.Current as Ciclo;
		}

		/// <summary>
		/// 
		/// </summary>
		private void OnCiclosPropertyChanged()
		{
			_ciclosFechasView.ciclosBindingSource.DataSource = Ciclos;
			_ciclosFechasView.ciclosBindingSource.CurrentChanged += SetCurrentCiclo;
			SetCurrentCiclo(_ciclosFechasView.ciclosBindingSource, new EventArgs());
		}

		private void OnCicloPropertyChanged()
		{
			LoadCiclosFechas();
		}

		#endregion
	}
}
